package com.peng.community.controller;

import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.DiscussPost;
import com.peng.community.entity.Page;
import com.peng.community.service.DiscussPostService;
import com.peng.community.service.UserService;
import com.peng.community.service.impl.ElasticSearchService;
import com.peng.community.service.impl.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    ElasticSearchService elasticSearchService;

    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    UserService userService;

    @Autowired
    LikeService likeService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) {
        org.springframework.data.domain.Page<DiscussPost> searchRequest = elasticSearchService.search(keyword, page.getCurrent() - 1, page.getLimit());
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (searchRequest != null) {
            //聚合页面要显示的数据
            discussPosts = searchRequest.stream().map(
                    post -> {
                        Map<String,Object> map = new HashMap<>();
                        map.put("user", userService.findUserById(post.getUserId()));
                        map.put("post", post);
                        map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                        return map;
                    }
            ).collect(Collectors.toList());
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);

        //设置分页信息
        page.setRows(searchRequest == null ? 0 : (int)searchRequest.getTotalElements());
        page.setPath("/search?keyword=" + keyword);

        return "/site/search";
    }
}
